import axios from 'axios';
import { useAuthorizationStore } from '../stores/authorization';
import { getCookie } from './index';
import { ElLoading, ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

const userStore = useAuthorizationStore();
const router = useRouter();

const apiClient = axios.create({
    headers: {
        'Content-Type': 'application/json',
    },
    timeout: 100000,
});

let loading: any;
const showLoading = () => {
    loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })

}

const hideLoading = () => {
    loading.close()
}

// 请求拦截器
apiClient.interceptors.request.use(
    (config) => {
        showLoading();
        if (userStore.authorization) {
            config.headers.Authorization = `${userStore.authorization}`;
        }
        config.headers['x-csrf-token'] = getCookie('csrfToken');
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
apiClient.interceptors.response.use(
    (config) => {
        hideLoading();
        if (config && config.data) {
            if (config.data.code === 401) {
                ElMessage({
                    showClose: true,
                    message: config.data.msg,
                    type: 'error',
                })
                console.log(router);
                userStore.clearAuthorization();
                window.location.replace('/login');
            }
            if (config.data.code === 0) {
                ElMessage({
                    showClose: true,
                    message: config.data.msg,
                    type: 'error',
                })
            }

        }
        // const userStore = useAuthorizationStore();
        // if (userStore.authorization) {
        //     config.headers.Authorization = `${userStore.authorization}`;
        // }
        return config;
    },
    (error) => {
        hideLoading();
        ElMessage({
            showClose: true,
            message: error,
            type: 'error',
        })
        if (error.status === 403) { // 清除token
            userStore.clearAuthorization();
        }

        return Promise.reject(error);
    }
);

export default apiClient;